package org.example.http;

import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class HttpServletResponseImpl implements HttpServletResponse {

    private Socket socket;
    private OutputStream outputStream;
    private Map<String,String> headers = new LinkedHashMap<>();
    private int status;
    private String msg;
    // 字符数组输出流(资源流), 输出数据到堆内存中, 并且通过 getString 可以获取到内容
    private CharArrayWriter charArrayWriter = new  CharArrayWriter();
    // 打印输出流(处理流)
    private PrintWriter printWriter = new PrintWriter(charArrayWriter);

    public HttpServletResponseImpl(Socket socket) {
        this.socket = socket;
        try {
            outputStream = socket.getOutputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public PrintWriter getWriter() {
        return printWriter;
    }

    @Override
    public OutputStream getOutputStream() {
        return outputStream;
    }

    @Override
    public void setContentType(String type) {
        headers.put("Content-Type", type);
    }

    @Override
    public void setStatus(int status, String msg) {
        this.status = status;
        this.msg = msg;
    }

    @Override
    public void setHeader(String name, String value) {
        headers.put(name, value);
    }

    @Override
    public void flushBuffer() throws IOException {
        // 设置默认的结果码
        if(status == 0){
            status = 200;
            msg = "OK";
        }
        // 响应头行
        outputStream.write(String.format("HTTP/1.1 %d %s\r\n", status, msg).getBytes());
        // 响应头
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            outputStream.write(String.format("%s: %s\r\n", entry.getKey(), entry.getValue()).getBytes());
        }
        // 输出cookie
        if(cookies.isEmpty() ==  false){
            for (int i = 0; i < cookies.size(); i++) {
                Cookie cookie = cookies.get(i);
                outputStream.write(String.format("Set-Cookie: %s\r\n", cookie.toString()).getBytes());
            }
        }
        // 空行
        outputStream.write("\r\n".getBytes());
        // 响应体
        outputStream.write(charArrayWriter.toString().getBytes());
    }

    @Override
    public void sendRedirect(String location) {
        headers.put("Location", location);
        status = 302;
        msg = "Redirect";
    }

    List<Cookie> cookies = new ArrayList<>();
    @Override
    public void addCookie(Cookie cookie) {
        cookies.add(cookie);
    }
}
